
const fs = require('fs')
const URL = require('url')
const moment = require('moment')
const download = require('download')
const inquirer = require('inquirer')
const shelljs = require('shelljs')
const print = require('../../lib/print')
const superagent = require('superagent')
const charset = require('superagent-charset')
const cheerio = require('cheerio')
charset(superagent)

// 日历桌面壁纸资源网站
// 其他资源网站：
// - http://www.win4000.com/zt/rili_2.html
// - http://www.netbian.com/rili/index.htm
const calendarSources = [
    'http://www.jj20.com/bz/jxbz/'
]
// 选用的资源网站
var baseUrl = null
// 日历图片保存的路径
const save_path = '/Users/caoyq/Pictures/美桌/calendar'
const year_month = moment().format('YYYY-MM')


module.exports = async function () {
    try {
        let has_calendar_image = await isExistYMCalendarImageInSavePath()
        if (!has_calendar_image) { // 没有则先爬取再下载
            baseUrl = await initParams()
            // baseUrl = calendarSources[0]
            var randomImages = await crawlingAllTypeCalendarImagesFromJJ20()

            // 下载
            await Promise.all(randomImages.map((url, index) => {
                if (url.length > 0) {
                    let img_path = `${save_path}/${year_month}-${index + 1}.jpg`
                    download(url).pipe(fs.createWriteStream(img_path))
                    console.log(`下载图片(${index}) - ${url}`)
                }
            }))
        }
        // 统一设置桌面
        print.successLog('图片资源已就绪')
        settingDesktopPicture()
    } catch (error) {
        console.log(error)
    }
}

/*
 * 在保存路径下是否已存在当前年月的日历图片
 * @return true：已存在
 */
function isExistYMCalendarImageInSavePath() {
    return new Promise((resolve, reject) => {
        let files = fs.readdirSync(save_path)
        files.forEach((file) => {
            if (file.includes(year_month)) {
                return resolve(true)
            }
        })
        resolve(false)
    })
}

/*
 * 自定义资源
 */
function initParams() {
    let promptList = [
        {
            type: "list",
            message: "请选择图片来源：",
            name: "sourceType",
            choices: calendarSources,
        }
    ]
    return new Promise((resolve, reject) => {
        inquirer.prompt(promptList)
            .then(answer => {
                resolve(answer.sourceType)
            })
    })
}

/*
 * 从 jj20.com 获取日历资源
 * @return 返回可直接下载的图片链接数组
 */
async function crawlingAllTypeCalendarImagesFromJJ20() {
    let link = await findCurrentYMCalendarFromJJ20()
    // link 只是 path，缺少 host，组装为完整链接
    link = `http://www.jj20.com${link}`
    let lpImages = await loopFindCurrentYMCalendarImagesFromJJ20(link)
    return lpImagesTranstromToDownloadImages(lpImages) 

    /*
     * 从网站日历中，找到当前年月的日历资源（最新的在最前面）
     * @return 返回当前年月日历链接
     */
    function findCurrentYMCalendarFromJJ20() {
        return new Promise((resolve, reject) => {
            superagent.get(baseUrl)
                .charset('')
                .end((err, sres) => {
                    let _link = null
                    if (err) {
                        reject(err)
                        return
                    }
                    let $ = cheerio.load(sres.text)
                    // 待优化：最新的在前面，其实只需要获取一次就行
                    $('div.g-box-1200 ul.picbz li a')
                        .each(function() {
                            // 不能用箭头函数
                            let href = $(this).attr('href')
                            let title = $(this).find('img').attr('alt')
                            let ym = moment().format('YYYY年M月')
                            if (title && title.includes(ym)) {
                                _link = href
                            }
                        })
                    if (_link.length) {
                        resolve(_link)
                        return
                    }
                    throw '暂无当前年月的日历'
                })
        })
    }

    /*
     * 基于当前年月日历 link，循环遍历获取对应预览图片的链接
     * @return 返回预览的图片链接数组
     */
    function loopFindCurrentYMCalendarImagesFromJJ20(link) {
        return new Promise((resolve, reject) => {
            superagent.get(link)
                .charset('UTF-8')
                .end((err, sres) => {
                    let items = []
                    if (err) {
                        reject(err)
                        return
                    }
                    let $ = cheerio.load(sres.text)
                    $('div.wzfz.tu.mt2 div.tu-se div.tu-in div.tu-st ul#showImg.fix li img')
                        .each(function() {
                            // 去除末尾的预览格式字符
                            let src = $(this).attr('src')
                            src = src.replace('-lp', '')
                            items.push(src)
                        })
                    resolve(items)
                })
        })
    }

    /*
     * 将预览图片转化为 1920x1080(电脑分辨率) 的图片
     * @return 返回最终可下载图片链接数组
     */
    function lpImagesTranstromToDownloadImages(lpImages) {
        // 转化的链接 (无法实现，无法下载)
        // let downloadUrlHost = 'http://cj.jj20.com/2020/down.html?picurl='
        // 可下载图片的域名 pic.jj20 也会存在问题，出现图片无法展示的问题(目前看应该网速的问题了)
        // let _host = 'http://pic.jj20.com'
        // 由于上述都存在问题，暂时用默认的域名了
        let _host = 'http://img.jj20.com'
        var result = []
        lpImages.forEach(element => {
            let p = URL.parse(element)
            result.push(`${_host}${p.path}`)
        })
        return result
    }
}

/*
 * 设置桌面背景，从本地当月日历图片中随机使用一张
 */
function settingDesktopPicture() {
    let files = fs.readdirSync(save_path)
    let result = files.filter(file => {
        if (file.includes(year_month)) {
            return file
        }
    })
    let randomIndex = Math.floor((Math.random() * result.length) + 1)
    let randomImage = `${save_path}/${result[randomIndex]}`
    let cmd = `osascript -e "tell application \\"Finder\\" to set desktop picture to POSIX file \\"${randomImage}\\""`
    shelljs.exec(cmd)
    print.successLog('已设置新的桌面图片')
}